﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Utilities.Helper;

namespace Utilities.Dictionary
{
    public class ObjectUtils
    {
        private ObjectUtils()
        {
        }

        /// <summary>
        /// Creates a Dictionary containing the fields names and the the values of the given object.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IDictionary<string, string> CreateDictionary(Object obj)
        {
            try
            {
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                Type ThisType = obj.GetType();
                IEnumerable<PropertyInfo> props = ThisType.GetRuntimeProperties();

                foreach (PropertyInfo prop in props)
                {
                    object ThisValue = PropertyHelperExtensions.CompileGetValueOfProperty(prop.Name, obj);

                    if (ThisValue != null)
                    {
                        if (prop.PropertyType == typeof(IEnumerable<>))
                        {
                            //Invalid IEnumerable List argument in the data 
                            throw (new ArgumentException("Lists are valid vlaues for parameter dictionary"));
                        }

                        KeyValuePair<string, string> KeyValue = new KeyValuePair<string, string>(prop.Name, ThisValue.ToString());
                        if (KeyValue.Key.Contains("ThrowOnInvalidPropertyName")) break;
                        dictionary.Add(KeyValue.Key, KeyValue.Value);
                    }
                }

                return dictionary;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return null;
        }
    }
}
